package com.lry.sign;

import com.itextpdf.io.codec.Base64;
import com.itextpdf.signatures.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;

/**
 * @author Ethan
 * @version 1.0
 * @description: TODO
 * @date 2021/6/24 0024
 */
public class SignService {
    public static final String KEYSTORE = "D:\\test\\sign\\store\\ks";
    public static final char[] PASSWORD = "password".toCharArray();
    public static String sign(String toSignHash,String hashAlgorithm) throws GeneralSecurityException, IOException {
        BouncyCastleProvider providerBC = new BouncyCastleProvider();
        Security.addProvider(providerBC);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(KEYSTORE), PASSWORD);
        String alias = ks.aliases().nextElement();
        Certificate[] chain = ks.getCertificateChain(alias);
        PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
        PrivateKeySignature signature = new PrivateKeySignature(pk, hashAlgorithm, "BC");
        BouncyCastleDigest digest = new BouncyCastleDigest();

        PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, digest, false);
        byte hash[] = Base64.decode(toSignHash);
        byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, PdfSigner.CryptoStandard.CMS, null, null);
        byte[] extSignature = signature.sign(sh);
        sgn.setExternalDigest(extSignature, null, signature.getEncryptionAlgorithm());
        ITSAClient tsaClient = new TSAClientBouncyCastle(SignInfo.TSA_URL, "", "",4096, "SHA-512");
        byte[] pck7 =  sgn.getEncodedPKCS7(hash, PdfSigner.CryptoStandard.CMS, tsaClient, null, null);
        return Base64.encodeBytes(pck7);
    }
}
